<?php
/**
 * 签约纪录增加车主id
 * @author angl
 */

date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}

$db = init_db();
$list = $db->where('status',0)->get('auth_employee_group');
logUtil("共".count($list)."条纪录",'INFO');
$counter = 0;
foreach($list as $key=>$value){
    if(!empty($value['rules'])){
        $rules = explode(",", $value['rules']);
        foreach ($rules as $k=>$r){
            $rule = $db->where('id',$r)->getOne('emp_auth_rule');
            if($rule['pid']!=0){
                 if(!in_array($rule['pid'],$rules)){
                     array_push($rules,$rule['pid']);
                 }
            }else{
                $childRulesList = $db->where("pid",$rule['id'])->get('emp_auth_rule');
                $childRules = [];
                foreach ($childRulesList as $ck=>$cv){
                    $childRules[] = $cv['id'];
                }
                $array_intersect = array_intersect($rules,$childRules);
                if(empty($array_intersect)){
                    unset($rules[$k]);
                }
            }
        }
        $rulesString = implode(",",array_unique($rules));
        $res = $db->where('id',$value['id'])->update('auth_employee_group',['rules'=>$rulesString]);
        if($res!==false){
            logUtil($value['title']." 更新完成","INFO");
        }
    }
}
logUtil($counter." 条数据处理完成","INFO");
